import type { AppProps } from 'next/app';
import { Router, useRouter } from 'next/router';
import NProgress from 'nprogress';
import { useGlobalStore } from '@/store/global';
import { Suspense, useEffect } from 'react';
import { useConfirm } from '@/hooks/useConfirm';
import { throttle } from 'lodash';
import { sealosApp, createSealosApp } from 'sealos-desktop-sdk/app';
import { SEALOS_DOMAIN, loadInitData } from '@/store/static';
import Head from 'next/head';
import { loader } from '@monaco-editor/react';
import { monacoTheme } from '@/constants/theme';

// Client-side Monaco configuration
if (typeof window !== 'undefined') {
  import('monaco-editor').then((monaco) => {
    loader.config({ monaco });
  });
}

import 'nprogress/nprogress.css';
import '@/styles/globals.css';

//Binding router events.
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());

export default function App({ Component, pageProps }: AppProps) {
  const router = useRouter();
  const { setScreenWidth, setLastRoute } = useGlobalStore();
  // const { Loading } = useLoading();
  const { openConfirm, ConfirmChild } = useConfirm({
    title: 'Redirect Notice',
    content: 'This app cannot run standalone. Click confirm to open Sealos Desktop.'
  });

  // app init
  useEffect(() => {
    NProgress.start();

    const response = createSealosApp();

    (async () => {
      try {
        const res = await sealosApp.getSession();
        localStorage.setItem('session', JSON.stringify(res));
        console.log('app init success');
      } catch (err) {
        console.log('App is not running in desktop');
        if (!process.env.NEXT_PUBLIC_MOCK_USER) {
          localStorage.removeItem('session');
          openConfirm(() => {
            window.open(`https://${SEALOS_DOMAIN}`, '_self');
          })();
        }
      }
    })();
    NProgress.done();

    return response;
  }, [openConfirm]);

  // add resize event
  useEffect(() => {
    const resize = throttle((e: Event) => {
      const documentWidth = document.documentElement.clientWidth || document.body.clientWidth;
      setScreenWidth(documentWidth);
    }, 200);
    window.addEventListener('resize', resize);
    const documentWidth = document.documentElement.clientWidth || document.body.clientWidth;
    setScreenWidth(documentWidth);

    return () => {
      window.removeEventListener('resize', resize);
    };
  }, [setScreenWidth]);

  // init
  useEffect(() => {
    loadInitData();
  }, []);

  // record route
  useEffect(() => {
    return () => {
      setLastRoute(router.asPath);
    };
  }, [router.asPath, router.pathname, setLastRoute]);
  return (
    <>
      <Head>
        <title>Kube Panel</title>
        <meta name="description" content="Generated by Sealos Team" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Component {...pageProps} />
      <ConfirmChild />
    </>
  );
}
